import React from 'react';
import PropType from 'prop-types';
import { observer, inject } from 'mobx-react';
import PJ from '../../stores/programmer_joke'
import JokeModel from '../joke_model/index';
import './index.scss';

@inject((stores) => {
  const store = {
    pj: stores.pj,
  }
  return store
})
@observer
class ProgrammerJoke extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      jokeList: [],
      showModel: false,
      willShowIndex: '',
    }
    this.handleJokeItemClick = this.handleJokeItemClick.bind(this)
    this.closeModel = this.closeModel.bind(this)
  }
  componentDidMount() {
    this.getList();
    this.props.pj.getPj(this.props.cateId, this.props.count)
  }
  componentWillUnmount() {
    this.props.pj.cancel()
  }
  // 获取joke
  getList() {
    // 参数
    const { cateId, count } = this.props
    this.props.pj.getPj(cateId, count)
  }
  // 点击joke标题淡出modal框
  handleJokeItemClick(index) {
    this.setState({
      showModel: true,
      willShowIndex: index + 1,

    })
  }
  // 关闭modal框
  closeModel() {
    this.setState({
      showModel: false,
    })
    document.removeEventListener('keydown', this.handleClose);
  }
  asyncBootstrap() {
    return new Promise((resolve, reject) => {
      const { count, cateId } = this.props
      this.props.pj.getPj(cateId, count)
        .then(() => {
          resolve(true)
        })
        .catch(reject)
    })
  }
  render() {
    const jokeList = this.props.pj.jokeList.get(`list${this.props.cateId}1`);
    return (
      <div className="programmer-joke">
        <span className="title-text">
          放松心情
        </span>
        <ul className="programmer-joke-list">
          {jokeList && jokeList.length ? jokeList.map((item, index) => (
            <li
              className={index === 0 ? 'hot' : ''}
              key={item.id}
              onClick={() => { this.handleJokeItemClick(index) }}
            >
              <span>{item.title.rendered}</span>
            </li>
          )) :
          <div className="loading">加载中</div>
          }
        </ul>
        {this.state.showModel ? <JokeModel activeIndex={this.state.willShowIndex} handleClose={this.closeModel} data={jokeList} cateId={this.props.cateId} /> : ''}
      </div>
    )
  }
}
export default ProgrammerJoke;
ProgrammerJoke.propTypes = {
  count: PropType.number,
  cateId: PropType.number,
  pj: PropType.instanceOf(PJ),
}
